
import html2pdf from "html2pdf.js";
import axios from "axios";
import Cookies from "js-cookie";
import moment from "moment";

/**
 * @param {*} desc 错误提示
 * @param {*} type 错误类别
 * @param {*} time 显示时间
 */
function toast(desc, type = 'error', time = 3) {
    ELEMENT.Message({
        dangerouslyUseHTMLString: true,
        message: desc,
        type: type,
        duration: time * 1000
    })
}

/**
 * 将html转为pdf文件，返回woker Obj
 */
export function htmlToPdf(pages, name) {
    const opt = {
        filename: name + ".pdf",
        image: {
            type: "jpeg",
            quality: 0.98,
        },
        html2canvas: {
            dpi: 192,
            scale: 2,
            letterRendering: true,
        },
        jsPDF: {
            unit: "mm",
            format: "a4",
            orientation: "portrait",
        },
    };

    let worker = html2pdf();

    for (let i = 0; i < pages.length; i++) {
        worker = worker
            .set(opt)
            .from(pages[i])
            .toContainer()
            .toCanvas()
            .toPdf()
            .get("pdf")
            .then((pdf) => {
                if (i < pages.length - 1) {
                    pdf.addPage();
                }
            });
    }
    return worker
}

/**
 * 上传pdf文件
 * @param {*} pdfFile 
 */
export function uploadPdfFile(pdfFile) {
    const form = new FormData();
    form.append("url", pdfFile);
    form.append("is_msg", true);
    form.append("is_schedule", true);
    const config = {
        headers: {
            "Content-Type": "multipart/form-data",
            "X-CSRFToken": Cookies.get("csrftoken"),
        },
    };
    axios
        .post("/api/Work/Files/", form, config)
        .then((res) => {
            if (res) {
                toast('文件上传成功', 'success')
            }
        })
        .catch(function (error) {
            toast("已取消上传文件");
        });
}

/**
 * 不同文件类型导出，生成文件名
 */
export function getYearReportName(record, showUser = false) {
    const { user, type, year, date_type, date, dateType} = record || {}
    const baseStr = showUser ? 
        user :
        `${year ? year : moment(date).year()}年${dateType || date_type}`
    if (type === "person") {
      return baseStr + "个人履职情况汇报";
    } else if (type === "unit") {
      return baseStr + "工作情况汇报";
    } else {
      return "战役/重点工作" + baseStr + "工作情况汇报";
    }
}